<?php
class listViewWidget extends dpWidget
{     
	//变量     
	private $_var;

	//模型列表
	private $_models;

	//分页
	private $_page;

	//字段列表
	private $_field = array();

	protected function init()
	{
		$this->setViewPath('widget'.DS.'listview'.DS.'view');
		if (is_array($this->options['model'])) {
			
		} else {
			$this->_models = new $this->options['model'];
		}
		if (isset($_GET['per_page'])) {
			$this->_var['per_page'] = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 20;
		} else {
			$this->_var['per_page'] = isset($this->options['per_page']) ? $this->options['per_page'] : 20;
		}

		$this->options['edit'] = isset($this->options['edit']) ? $this->options['edit'] : '';
		$this->options['op_width'] = isset($this->options['op_width']) ? $this->options['op_width'] : 90;
		$this->_var['numone_no_del'] = isset($this->options['numone_no_del']) ? true : false;
		$this->_getUri();
	}

	protected function main()
	{

		return $this->_getHtml();
	}

	private function _getUri()
	{
		$qs = explode('&', $_SERVER['QUERY_STRING']);
		$t = '';
		foreach ($qs as $g) {
			$temp = explode('=', $g);
			$get[$temp[0]] = empty($temp[1]) ? '' : $temp[1];
		}
		unset($get['m'], $get['c'], $get['a']);
		$this->_var['url'] = $get;
		if (!empty($get)) {
			foreach ($get as $k => $v) {
				$t .= $k.'='.$v.'&';
			}
		}
		return trim($t, '&');
	}

	private function _getData()
	{
		foreach ($this->options['show_data'] as $k => $v) {
			$this->_field[] = $k;
		}
		$this->_var['sort'] = $sort = isset($_GET['sort']) ? $_GET['sort'] : $this->_field[0];
		$this->_var['type'] = $type = isset($_GET['type']) ? $_GET['type'] : 'DESC';
		$order = $sort . ' ' . $type;
		$this->_var['data']  	= $this->_models->recently($order, $this->_initPage())->findsByAttribute($this->_field);
		$this->_var['page_str']	= $this->page->display(array('first', 'prev', 'nums', 'next', 'last'));
		$this->_var['url'] 		= $this->page->getUrl();
		$this->_var['buttons']  = isset($this->options['buttons']) ? $this->options['buttons'] : array();
	}

	private function _initPage()
	{
		$meta = $this->_models->getColumnName();
		$this->_models->findsByAttribute($meta[0]);
		$this->page = new dpPage(
			array(
				'base_url'   => $this->options['page_base_url'],
				'total_rows' => $this->_models->count(),
				'per_page'   => $this->_var['per_page'],
				'num_links'  => 2,
				'prev_link'  => '«',
				'next_link'  => '»',
				'ajax_func'  => 'listviewGotoPage',
				'query_string' 	  => $this->_var['url'],
				'first_tag_style' => 'first',
				'last_tag_style'  => 'last',
				'page_container_tag_style' => 'page',
			)
		);
		return $this->page->getSqlLimit();
	}

	private function _getHtml()
	{
		$this->_getData();
		$html  = '<link rel="stylesheet" type="text/css" href="'.$this->_getUrl().'listview.css" />';
		$html .= '<div id="' . $this->options['id'] . '">';
		$html .= '<table class="gird-list" cellspacing="0" cellpadding="0" border="0" width="'.$this->options['table_width'].'">';
		$html .= '<tr class="caption"><td width="25" valign="middle" title="全选"><input type="checkbox" id="listview_select_all" /></td>';
			foreach ($this->options['show_data'] as $name => $set) {
				$class = $this->_var['sort'] == $name ? 'class="lv-sort" ' : '';
				$type  = $this->_var['type'] == 'ASC' ? 'type="asc" ' : 'type="desc" ';
				if (empty($class)) {
					$url = $this->_var['url'] . '&sort='.$name.'&type=DESC';
				} else {
					if ($this->_var['type'] == 'ASC') {
						$url = $this->_var['url'] . '&type=DESC';
					} else {
						$url = $this->_var['url'] . '&type=ASC';
					}
				}
				$html .= '<td '.$class.$type.'onclick="listviewGotoPage(\''.$url.'\');" width="'.$set['width'].'">'.$set['name'].'</td>';
			}
		$html .= '<td width="'.$this->options['op_width'].'" style="cursor:auto;">操作</td>';
		$html .= '</tr>';
			foreach ($this->_var['data'] as $k => $v) {
				$val   = $v[$this->_field[0]];
				if ($val == 1 && $this->_var['numone_no_del']) {
					$html .= '<tr class="list"><td></td>';
				} else {
					$html .= '<tr class="list"><td class="top_delete"><input type="checkbox" class="list_select" value="'.$val.'" /></td>';
				}
				foreach ($this->options['show_data'] as $name => $set) {
					$html .= '<td>'.$v[$name].'</td>';
				}
				$html .= '<td class="op">';
				if (isset($this->options['links']) && is_array($this->options['links'])) {
					$a = '';
					foreach ($this->options['links'] as $link) {

						$url = $link['url'];
						$pk = $this->_models->primaryKey();
						$url_p = $url.'&'.$pk.'='.$v[$this->_field[0]];

						if (!empty($link['alert'])) {
							$click = 'onclick="execute('.$v[$this->_field[0]].', \''.$url.'\', \'del\', this);"';
						} else {
							$click = 'onclick="con_load(\''.$url.'\', \''.$url_p.'\');"';
						}

						$a .= '<a href="javascript:;" class="col-000" '.$click.'>'.$link['text'].'</a> | ';
					}
				$html .= substr($a, 0, -2).'</td>';
				} else {
					if ($val != 1 && $this->_var['numone_no_del']) {
						$html .= '<a href="javascript:;" onclick="execute('.$v[$this->_field[0]].', \''.$this->options['delete'].'\', \'del\', this);"><img src="'.$this->_getUrl().'/images/ljt.png" /></a>　';
					}
					$html .= '<a href="javascript:;" onclick="execute('.$v[$this->_field[0]].', \''.$this->options['edit'].'\', \'edit\', false);"><img src="'.$this->_getUrl().'/images/edit.png" /></a></td>';
				}
				$html .= '</tr>';
			}
		$html .= '<tr class="listview-page"><td width="15" title="全选"><input type="checkbox" id="page_select_all" /></td>';
		$html .= '<td align="right" colspan="'.(count($this->options['show_data'])+1).'">';
			if ($this->_var['buttons'] !== array()) {
				$html .= '<div id="lv-buttons">';
				foreach ($this->_var['buttons'] as $button) {
					$html .= '<a href="javascript:;" onclick="gtb(\''.$button['name'].'\', \''.$button['url'].'\');" class="listview-bt">'.$button['name'].'</a>';
				}
				$html .= '</div>';
			}
		$html .= $this->_var['page_str'];
			if (!empty($this->_var['page_str'])) {
				$html .= '<div class="per">每页 <input type="text" value="'.$this->_var['per_page'].'" class="per_page" /> 条</div>';
			}
		$html .= '</td></tr>';
		$html .= '</table>';
		$html .= '</div>';
		$html .= $this->_getJs();
		return $html;
	}

	private function _getJs()
	{
return <<<EOF
<script type="text/javascript">
$(function(){
	$('#listview_select_all, #page_select_all').click(function(){
		if ( $(this).is(':checked') ){
			$('.list_select, #listview_select_all, #page_select_all').attr('checked', true);
			$('.list_select').addClass('box_select');
			$('.list').addClass('list-tr');
			$('.listview-bt').fadeIn(50);
		} else {
			$('.list_select, #listview_select_all, #page_select_all').removeAttr('checked');
			$('.list_select').removeClass('box_select');
			$('.list').removeClass('list-tr');
			$('.listview-bt').fadeOut(50);
		}
	});

	$('.list_select').click(function(){
		if ($(this).is(':checked')) {
			$(this).addClass('box_select');
			$(this).parent().parent().addClass('list-tr');
		} else {
			$(this).removeClass('box_select');
			$(this).parent().parent().removeClass('list-tr');
		}
		if ($('.list-tr').length > 0) {
			$('.listview-bt').fadeIn(50);
		} else {
			$('.listview-bt').fadeOut(50);
		}
	});

	$('.list').children('td').not('.top_delete, .op').click(function(){
		input = $(this).parent().children('td').eq(0).children('input');
		if (input.is(':checked')) {
			$(this).parent().removeClass('list-tr');
			input.removeAttr('checked').removeClass('box_select');
		} else {
			$(this).parent().addClass('list-tr');
			input.attr('checked', true).addClass('box_select');
		}
		if ($('.list-tr').length > 0) {
			$('.listview-bt').fadeIn(50);
		} else {
			$('.listview-bt').fadeOut(50);
		}
	})

	var type = $('.lv-sort').attr('type');
	$('.lv-sort').append('<div class="sort_'+type+'"></div>');

	$('.per_page').keyup(function(event){
		if (event.which == 13) {
			url = '{$this->_var['url']}' + '&per_page='+$('.per_page').val();
			$('#main_content').load(url);
		}
	})

});

var gtb = function(n, u) {
	var param = '&{$this->_field[0]}=';
	$('.box_select').each(function(i){
		param += $('.box_select').eq(i).val() + ', ';
	})
	u = u + param.substr(0, param.length - 2);
	dpAlert(this, {
		callback : 'alerts',
		win    : true,
		title  : '提示',
		height : '230',
		content: '确定要对选择的信息进行 <span style="color:red">'+n+'</span> 操作吗！'
	});
	$('#ok_button').click(function(){
		$.getJSON(u, function(data){
			if (data.code == 0) {
				dpAlert(this, {
					callback : 'alerts',
					title  : '提示',
					height : '230',
					content:data.msg
				});
			} else {
				dpAlert(this, {
					callback : 'notice',
					content  : data.msg
				});
				$('#main_content').load('{$this->page->getUrl()}');
			}
		})
	})
}

var	listviewGotoPage = function(u) {
	$('#main_content').load(u);
}
var con_load = function(u, u1)
{
	$('.top_button').remove();
	content_load(u, u1);
}
var execute = function(id, u, t, s) {
	u += '&{$this->_field['0']}='+id;
	if (t == 'del') {
		dpAlert(this, {
			callback : 'alerts',
			win    : true,
			title  : '提示',
			height : '230',
			content: '确定要删除吗，该操作不可恢复！'
		});
		$('#ok_button').click(function(){
			$.getJSON(u, function(data){
				if (data.code == 0) {
					dpAlert(this, {
						callback : 'alerts',
						title  : '提示',
						height : '230',
						content:data.msg
					});
				} else {
					dpAlert(this, {
						callback : 'notice',
						content  : data.msg
					});
					$(s).parent().parent().fadeOut(50);
				}
			})
		})
	} else {
		$('.top_button').remove();
		listviewGotoPage(u);
		top_menu('{$this->options['edit']}');
	}
}
</script>
EOF;
	}

	private function _getUrl()
	{
		return D::homeUrl() . 'app/' . str_replace("\\", '/', $this->getViewPath()) . '/';
	}
}
?>